package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.vos.SearchArticleVo;
import com.heima.search.service.ArticleSearchService;
import com.heima.search.service.SearchHistoryService;
import com.heima.utils.thread.ApUserThreadLocalUtil;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 陈辉
 * @data 2023 11:03
 */

@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {


    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private SearchHistoryService searchHistoryService;

    /**
     * app文章搜索
     *
     * @param searchDto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto searchDto) {
        if (searchDto == null || StringUtils.isBlank(searchDto.getSearchWords()))
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        try {

            //只有当前登录的是有效用户
            if (ApUserThreadLocalUtil.getUser()!= null && !ApUserThreadLocalUtil.getUser().equals("0")) {
                //才保存搜索历史记录
                searchHistoryService.save(searchDto.getSearchWords());
            }


            //1. 创建一个查询请求request
            SearchRequest searchRequest = new SearchRequest("app_info_article");

            //2. 构建查询的请求体参数
            //2.1 查询条件  -- boolQuery
            searchRequest.source().query(QueryBuilders.boolQuery()
                    .must(QueryBuilders.multiMatchQuery(searchDto.getSearchWords(),"title","content"))
                    .filter(QueryBuilders.rangeQuery("publishTime").lte(searchDto.getMinBehotTime()))
            );
            //2.2 分页条件
            searchRequest.source().from(searchDto.getPageNum());
            searchRequest.source().size(searchDto.getPageSize());

            //2.3 排序条件
            searchRequest.source().sort("publishTime", SortOrder.DESC);

            //2.4 高亮设置
            searchRequest.source().highlighter(new HighlightBuilder().field("title")
                    .preTags("<font style='color: red; font-size: inherit;'>")
                    .postTags("</font>"));


            //3. 发送请求给es，进行数据查询
            SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

            //4. 解析es响应的结果数据并返回给前端
            SearchHit[] hits = response.getHits().getHits();
            List<SearchArticleVo> list = new ArrayList<>();

            //4.1 遍历hits,得到每一个source
            for (SearchHit hit : hits) {
                String sourceJson = hit.getSourceAsString();
                SearchArticleVo articleVo = JSON.parseObject(sourceJson, SearchArticleVo.class);
                articleVo.setH_title(articleVo.getTitle());
                list.add(articleVo);

                //4.2 如果有highlight，需要处理高亮字段
                HighlightField highlightField = hit.getHighlightFields().get("title");
                if (highlightField != null){
                    String highlightTitle = highlightField.getFragments()[0].toString();
                    articleVo.setH_title(highlightTitle);
                }
            }
            return ResponseResult.okResult(list);

        }catch (Exception e){
            e.printStackTrace();
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }
}
